package com.google.code.jcooky.rpc.server;

import java.lang.reflect.Method;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.StringTokenizer;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.apache.log4j.Logger;

import com.google.code.jcooky.rpc.utils.JsonUtils;

public class RPCServlet extends HttpServlet {

	private static Logger logger = Logger.getLogger(RPCServlet.class);
	
	private ServiceRegistry services = new ServiceRegistry();
	private ServiceExecutor executor = new ServiceExecutor();
	
	private String getServiceInterfaceName(Class<?>[] interfaces) {
		for(Class<?> iface : interfaces) {
			if(iface.getName().endsWith("$Iface")) {
				return iface.getName();
			}
		}
		return null;
	}

	public void init() throws ServletException {
		String initServices = getServletConfig().getInitParameter("services");
		StringTokenizer tokenizer = new StringTokenizer(initServices, ", ");
		while(tokenizer.hasMoreTokens()) {
			String serviceName = tokenizer.nextToken();
			services.add(serviceName);
		}
	}
	
	public void doPost(HttpServletRequest request, HttpServletResponse response) {
//		try {
//			request.setCharacterEncoding("UTF-8");
//			response.setContentType("text/html;charset=UTF-8");
//			
//			String reqJson = URLDecoder.decode(request.getHeader("req_json"), "UTF-8");
//			
//			if(logger.isDebugEnabled()) {
//				logger.debug("Request Json = " + reqJson);
//			}
//			
//			JSONObject reqObj = JSONObject.fromObject(reqJson);
//
//			List<Object> args = new ArrayList<Object>();
//			if(reqObj.has("arguments")) {
//				JSONArray argArray = reqObj.getJSONArray("arguments");
//				
//			}
//			Object instance = instanceMap.get(reqObj.getString("service"));
//			Method method = instance.getClass().getMethod(reqObj.getString("method"), argTypes);
//			Object ret = method.invoke(instance, argValues);
//
//			JSONObject model = new JSONObject();
//			model.put("bean", ret == null ? null : ret.getClass().getName());
//			model.put("return", ret == null ? null : ret);
//
//			response.getWriter().write(model.toString());
//		} catch (Exception e) {
//			throw new RuntimeException(e);
//		}
	}
}
